package com.ruoyi.web.common.util.format;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.iot.domain.IotDataTermite;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 白蚁监测第三方工具类
 */
public class TermiteUtil {
    //登录
    private static final String API_URL_LOGIN = "http://106.15.236.221:8893/byjc/api/login.htm";

    //白蚁数据
    private static final String API_URL_Amnitro = "http://106.15.236.221:8893/byjc/api/monitordata/dataList.htm";
    //白蚁采集的设备-离线（测试设备编号非实际使用）
    private static final List<String>  excludeDevices = Arrays.asList(
        "BYM202411250012-040",
        "BYM202411250012-039",
        "BYM202411250012-038",
        "BYM202411250012-037",
        "BYM202411250012-036",
        "BYM202411250012-035",
        "BYM202411250012-034",
        "BYM202411250012-033",
        "BYM202411250012-032",
        "BYM202411250012-031",
        "BYM202411250012-030",
        "BYM202411250012-029",
        "BYM202411250014-025",
        "BYM202411250014-024",
        "BYM202411250014-023"
    );

    public static JSONObject login(String url, String username, String password)
    {

        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createPost(url);
        // 设置请求体参数为 form 格式
        request.form("usernameMonitor", username)
            .form("passwordMonitor", password);
        // 发送请求并获取响应
        String response = request.execute().body();
        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject;
    }

    public static JSONObject fetchDataWithToken(String url,String cookie)
    {
        // 创建 HttpRequest 对象
        HttpRequest request = HttpUtil.createPost(url);

        // 添加请求头，包含 token
        request.header("Cookie", "JSESSIONID=" + cookie);

        // 发送请求并获取响应
        String response = request.execute().body();

        // 将响应字符串解析为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(response);

        return jsonObject;
    }


    //没有将设备的采集时间赋值过去
    public static List<IotDataTermite> convertUnits() {
        String cookie = login(API_URL_LOGIN, "17340564756", "123456").get("sessionId").toString();

        JSONObject data = fetchDataWithToken(API_URL_Amnitro,cookie);
        List<JSONObject> dataListVOs = data.getByPath("dataListVOs", List.class);

        // 使用 Stream 过滤 + 转换
        List<IotDataTermite> result = dataListVOs.stream()
            .filter(item -> ! excludeDevices.contains(item.getStr("monitorLineName"))) // 排除 termiteDeviceList 中的数据
            .map(item -> {
                IotDataTermite termite = new IotDataTermite();
                String monitorLineName = item.getStr("monitorLineName");
//                termite.setMonitorLineName(monitorLineName);
                termite.setDeviceId(item.getStr("monitorLineName"));
                termite.setSinkData(item.getStr("sinkData"));
                termite.setSkingData(item.getStr("skingData"));
                termite.setValue(processTermiteData(item.get("deviceData"))); // deviceData 映射到 value
                termite.setReportTime(new Date()); // 可选：统一设置时间

//                // 使用 collectingTime 字段作为 reportTime（时间戳转 Date）
//                Long collectingTime = item.getLong("collectingTime");
//                if (collectingTime != null) {
//                    termite.setReportTime(new Date(collectingTime));
//                }
                // 根据 monitorLineName 设置 remoteId
                if (monitorLineName.contains("BYM202411250016")) {
                    termite.setRemoteId("4208217357");
                } else if (monitorLineName.contains("BYM202411250014")) {
                    termite.setRemoteId("4208218357");
                } else if (monitorLineName.contains("BYM202411250012")) {
                    termite.setRemoteId("4208219357");
                } else {
                    termite.setRemoteId("4208217357"); // 或默认值
                }

                return termite;
            })
            .collect(Collectors.toList());



        return result;
    }

    public static  Map<String, Object> convertParams(IotDataTermite dataTermite){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        fields.put("value", dataTermite.getValue());
        fields.put("report_time", dataTermite.getReportTime());
        fields.put("sink_data", dataTermite.getSinkData());
        fields.put("sking_data", dataTermite.getSkingData());
        map.put("fields", fields);
        Map<String, Object> tags = new HashMap<>();
        tags.put("device_id", dataTermite.getDeviceId());
        tags.put("remote_id", dataTermite.getRemoteId());
        map.put("tags", tags);
        return map;
    }

    public static  Map<String, Object> convertInfluxdbParams(IotDataTermite dataTermite){
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();
        fields.put("value", dataTermite.getValue());
        fields.put("report_time", dataTermite.getReportTime().getTime());
        fields.put("sinkData", dataTermite.getSinkData());
        fields.put("skingData", dataTermite.getSkingData());
        map.put("fields", fields);
        Map<String, Object> tags = new HashMap<>();
        tags.put("deviceId", dataTermite.getDeviceId());
        tags.put("remoteId", dataTermite.getRemoteId());
        map.put("tags", tags);
        return map;
    }

    /**
     * 处理termite数据
     * @param deviceDataObj
     */
    public static String processTermiteData(Object deviceDataObj) {
        if (deviceDataObj == null) {
            return "0";
        }

        String strVal = deviceDataObj.toString().trim();

        // 如果是 "0.0" 这种格式，就替换为 "0"
        if ("0.0".equals(strVal)) {
            return "0";
        }

        // 否则原样返回或进一步处理
        return strVal;
    }



    public static void main(String[] args) {
//        JSONObject login = login(API_URL_LOGIN, "17340564756", "123456");
//        System.out.println(login);
        List<IotDataTermite> termiteList = convertUnits();
        Map<String, Object> stringMapMap = convertParams(termiteList.get(0));
        System.out.println(stringMapMap);
    }
}
